﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AL.Helper;
using System.Threading;

namespace AL
{
    public partial class FormLoading : Form
    {
        public FormLoading()
        {
            InitializeComponent();
        }


        // 进度条时钟
        private void timer1_Tick(object sender, EventArgs e)
        {
            progressBar1.Maximum = CacheHelper.MaxCount;
            if (progressBar1.Maximum >= CacheHelper.CurrentCount) progressBar1.Value = CacheHelper.CurrentCount;

            if (progressBar1.Maximum - progressBar1.Value < 10) btn_Cancel.Visible = true;

            label1.Text = string.Format("{0} / {1}", CacheHelper.CurrentCount, CacheHelper.MaxCount);
            if (progressBar1.Value == progressBar1.Maximum)
            {
                btn_Cancel.Visible = false;
                this.Close();
            }
        }

        // 窗体加载
        private void FormLoading_Load(object sender, EventArgs e)
        {
            progressBar1.Maximum = 100;
            progressBar1.Value = 0;


            if (string.IsNullOrWhiteSpace(CacheHelper.OpenId) && CacheHolder.GetAccounts().Any())
            {
                CacheHelper.MaxCount = 0;
                CacheHelper.CurrentCount = 0;
                var count = CacheHolder.GetAccounts().Count;
                for (var index = 0; index < count; index++)
                {
                    Task.Factory.StartNew((object idx) =>
                    {
                        // 根据公众号获取文章列表
                        var articles = CacheHolder.GetArticles(CacheHolder.GetAccounts()[(int) idx].OpenId, 1, CacheHelper.LoginCookies);
                    }, index);
                }
            }
            else
            {
                CacheHelper.MaxCount = 0;
                CacheHelper.CurrentCount = 0;
                Task.Factory.StartNew(() =>
                {
                    // 根据公众号获取文章列表
                    var articles = CacheHolder.GetArticles(CacheHelper.OpenId, 1, CacheHelper.LoginCookies);
                });    
            }

            timer1.Interval = 300;
            timer1.Start();

            //// 获取单个 OpenId 模式
            //Task.Factory.StartNew(() =>
            //{
            //    // 根据公众号获取文章列表
            //    var articles = CacheHolder.GetArticles(CacheHelper.OpenId, 1, CacheHelper.LoginCookies); 
            //});

            //SpinWait.SpinUntil(() => CacheHelper.MaxCount == CacheHelper.CurrentCount, 300);
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            timer1.Stop();
            CacheHelper.MaxCount = 0;
            CacheHelper.CurrentCount = 0;
            btn_Cancel.Visible = false;
            this.Close();
        }

    }
}
